<!--
 * @Description: 
 * @Author: 张文韬
 * @Date: 2024-06-24 15:29:13
 * @LastEditTime: 2024-07-16 14:13:10
 * @LastEditors: 张文韬
 * @Reference: 
-->
<template>
  <div class="mb-10px flex flex-justify-end">
    <div class="flex items-center">
      <el-button
        v-for="(button, index) in handleButtons"
        :key="button.text"
        :type="button.type"
        @click="tableHandleClick(index)"
      >{{ button.text }}</el-button>
    </div>
  </div>
  <e-table 
    :data="tableData" 
    :columns="displayColumns" 
    :loading="loading"
    @select-all="handleSelectChange"
    @selection-change="handleSelectChange">
    <template #handleSlot="{scope}">
      <el-button type="warning" @click="edit(scope.row)" size="small">编辑</el-button>
      <el-button type="danger" @click="remove(scope.$index)" size="small">删除</el-button>
    </template>
  </e-table>
  <el-dialog
    v-model="dialogShow"
    title="受益人"
    :width="800"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <e-form
      v-if="dialogShow"
      class="mr-10px"
      ref="dialogForm"
      :form-options="formOptions"
      form-label-width="120px"
      :form-rules="formRules"
      :form-data-current="dialogFormCurrent"
      @cardTypeChange="changeCardType"
      @cardNumberChange="changeCardNumber"
      @birthChange="changeBirth"
    >
    </e-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

import { editFormOptions, editFormRules } from './form'
import columns from './columns'
import eTable from '@/components/e-table'
import idCardTool from "@/utils/id-card";
import { ElMessage, dayjs } from 'element-plus';
import EForm from '@/components/e-form';

// import { isIdCard } from "@/utils/id-card";
const emits = defineEmits(['benefitUpdate'])

// 默认证件类型
let defaultCardType = '0'
let defaultMoney = 20

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  data: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    default: () => []
  }
})


const dialogForm = ref(null)
const displayColumns = ref(columns)
const tableData = ref([])
const selectData = ref([])
const helpers = reactive({
  isSingle: false,
  relationShow: false,
  autoParse: true,
})

const handleButtons = [
  { text: '添加受益人', type: 'success' },
  { text: '删除选中', type: 'warning' },
  { text: '清空', type: 'danger' },
]


// dialog -------------------------------------------------------

// insurant：被保人  list-analysis: 只能名单分析   card-type
const dialogType = ref('add') 
const dialogFormCurrent = ref(null)
const formOptions = ref([...editFormOptions])
const formRules = reactive({...editFormRules})
const dialogShow = ref(false)

const changeCardType = (certificateType) => {
  const keys = ['age', 'birthday', 'gender']
  formOptions.value.map(o => {
    if (keys.indexOf(o.key) > -1) {
      o.props.disabled = certificateType == '0'
    }
  })
}
const changeCardNumber = (certificateNo, config) => {
  const { certificateType } = dialogForm.value.formData
  if (certificateType != '0' || !idCardTool.isIdCard(certificateNo)) return
  dialogForm.value.formData.age = idCardTool.getAge(certificateNo)
  dialogForm.value.formData.gender = idCardTool.getSex(certificateNo)
  dialogForm.value.formData.birthday = idCardTool.getBirth(certificateNo)
}

const changeBirth = (birthday) => {
  if (!birthday) return
  const formData = dialogForm.value.formData
  formData.age = dayjs().diff(dayjs(birthday), 'year')
}

const openDialog = (type = 'add') => {
  dialogType.value = type
  dialogShow.value = true
}

const closeDialog = () => {
  dialogShow.value = false
}

const handleCancel = () => {
  dialogForm.value&&dialogForm.value.handleRefresh()
  closeDialog()
  dialogFormCurrent.value = null
}

const handleConfirm = () => {
  saveInsurant()

}

const saveInsurant = () => {
  dialogForm.value.handleValidate(validate => {
    const o = { ...dialogForm.value.formData }
    if (validate) {
      if (dialogType.value == 'add') {
        tableData.value.push(o)
      }
      handleCancel()
    }
  })
}

const addUniqueRule = () => {
  const rules = [{ 
    validator: (rule, value, callback) => {
      const obj = tableData.value.find(o => dialogType.value == 'add'&&o.certificateNo == value)
      if (obj) {
        callback(new Error('该身份证号已存在'));
      } else {
        callback();
      }
    }, message: '该证件号码已存在', trigger: 'blur'
  }, { 
    validator: (rule, value, callback) => {
      const { certificateType } = dialogForm.value.formData
      if (certificateType == '0' && !(idCardTool.isIdCard(value))) {
        callback(new Error('身份证号码不符合规范'));
      } else {
        callback();
      }
    }, message: '身份证号格式错误', trigger: 'blur'
  }]
  formRules.certificateNo = editFormRules.certificateNo.concat(rules)
}

// table event -------------------------------------------------------
const tableHandleClick = (index) => {
  switch (index) {
    case 0:
      insert()
      break;
    case 1:
      removeSelected()
      break;
    case 1:
      clear()
      break;
  }
}

const insert = () => {
  console.log('insert');
  dialogFormCurrent.value = {
    id: dayjs().valueOf(),
    name: '',
    gender: '',
    certificateType: defaultCardType,
    certificateNo: '',
    birthday: '',
    age: '',
    phone: '',
    relationshipWithApplicant: '',
    rate: ''
  }
  openDialog()
}

const removeSelected = () => {
  if (selectData.value.length == 0) {
    ElMessage.warning('未选择名单')
    return
  }
  const temp = selectData.value.map(o => o.id)
  tableData.value = tableData.value.filter(o => temp.indexOf(o.id) < 0)
}

const remove = (index) => {
  tableData.value.splice(index, 1)
}

const clear = () => {
  tableData.value = []
}

const edit = (row) => {
  console.log(row);
  dialogFormCurrent.value = row
  openDialog('update')
}

const handleSelectChange = (e) =>  {
  selectData.value = e
}

// hooks -------------------------------------------------------
watch(() => props.data, (val) => {
  tableData.value = val
})

watch(() => helpers.relationShow, (val) => {
  if (val) {
    displayColumns.value = columns
    formOptions.value = editFormOptions
  }
  else {
    displayColumns.value = columns.filter(o => o.label != '与投保人关系')
    formOptions.value = editFormOptions.filter(o => o.key != 'relationshipWithApplicant')
  }
}, { immediate: true })

onMounted(() => {
  // addUniqueRule()
})

</script>
